<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;

class Cms_Gift_Record extends Model
{
    use HasFactory;

    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'cms_gift_record';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    protected $fillable = [
        'mid',
        'otherid',
        'gift_id',
        'nums',
        'fee',
        'income',
        'create_time',
        'update_time',
        'is_del'
    ];
    public function scopeNodel($query)
    {
        return $query->where('is_del', 0);
    }

    protected $hidden = [
        'is_del',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    public function hasOneMember()
    {
        return $this->hasOne('App\Models\Cms_Member', 'id', 'mid');
    }

    public function hasOneOtherMember()
    {
        return $this->hasOne('App\Models\Cms_Member', 'id', 'otherid');
    }

    public function hasOneGift()
    {
        return $this->hasOne('App\Models\Cms_Gift', 'id', 'gift_id');
    }

    public static function getFilter($filter)
    {
        return self::whereHas('hasOneMember', function ($query) use ($filter) {
            if (isset($filter['username']) && !empty($filter['username'])) {
                $query->where('username',  $filter['username'] );
            }
        })->whereHas('hasOneOtherMember', function ($query) use ($filter) {
            if (isset($filter['othername']) && !empty($filter['othername'])) {
                $query->where('username',  $filter['othername'] );
            }
        })->whereHas('hasOneGift', function ($query) use ($filter){
            if (isset($filter['name']) && !empty($filter['name'])) {
                $query->where('name',  $filter['name'] );
            }
        });
    }
}
